<template>
  <div>
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体区域 -->
    <el-card>
      <el-alert
        show-icon
        title="注意:只允许为第三级分类设置相关参数!"
        type="warning"
        :closable="false"
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="catelist"
            :props="{
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
              expandTrigger: 'hover',
            }"
            @change="cateListChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab标签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTagClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isTagButtonDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyCateAttr" stripe border>
            <!-- 展开行（显示参数） -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染出tag标签 -->
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  @close="handleClosed(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入按钮-->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteCateAttr(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性区域 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isTagButtonDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyCateAttr" stripe border>
            <!-- 展开行（显示属性） -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染出tag标签 -->
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  @close="handleClosed(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入按钮-->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteCateAttr(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性/参数区域 -->
    <el-dialog
      :title="'添加' + addInfo"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addDialogRuleForm"
        :rules="addDialogRules"
        ref="addDialogRef"
        label-width="100px"
      >
        <el-form-item :label="addInfo" prop="attr_name">
          <el-input v-model="addDialogRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性/参数区域 -->
    <el-dialog
      :title="'修改' + addInfo"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editDialogRuleForm"
        :rules="editDialogRules"
        ref="editDialogRef"
        label-width="100px"
      >
        <el-form-item :label="addInfo" prop="attr_name">
          <el-input v-model="editDialogRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
name:'',
  data() {
    return {
        //商品信息
        catelist:[],
        //选中的商品信息
        selectedCateKeys:[],
        //被选中的tag标签
        activeName:'many',
        //动态参数数据
        manyCateAttr:[],
        //静态参数数据
        onlyCateAttr:[],
        //添加属性/参数的窗口是否开启值
        addDialogVisible:false,
        //添加属性/参数的窗口信息
        addDialogRuleForm:{
          attr_name:'',
        },
        //添加属性/参数的窗口规则
        addDialogRules:{
          attr_name:[{required: true, message:'请输入参数名称', trigger: 'blur'}]
        },
        //修改属性/参数的窗口是否开启值
        editDialogVisible:false,
        //修改属性/参数的窗口信息
        editDialogRuleForm:{
          attr_name:'',
          attr_id:0,
        },
        //修改属性/参数的窗口规则
        editDialogRules:{
          attr_name:[{required: true, message:'请输入参数名称', trigger: 'blur'}]
        },


    }
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品信息
    async getCateList(){
      const {data:res}=await this.$http.get('categories');
      if(res.meta.status!==200) return this.$message.error('获取商品信息失败');
      this.catelist=res.data;
    },
    //选中的商品信息发生改变时
    cateListChange(){
      this.getCateAttr();
    },
    //选中的Tag发生改变时
    handleTagClick(){
      this.getCateAttr();
      // console.log(this.activeName);
    },
    //获取参数信息
    async getCateAttr(){
      if(this.selectedCateKeys.length!==3){
          this.selectedCateKeys=[];
          this.manyCateAttr=[];
          this.onlyCateAttr=[];
          return
      };
      //发送请求
      const {data:res}=await this.$http.get(`categories/${this.cateID}/attributes`,{params:{sel:this.activeName}});
      if(res.meta.status!=200) return this.$message.error('获取商品信息失败');
      
      res.data.forEach(item=>{
        //动态参数的属性值
        item.attr_vals=item.attr_vals?item.attr_vals.split(','):[];
        //输入框/按钮的显示与隐藏
        item.inputVisible=false;
        //输入框的值
        item.inputValue="";
      })
      // console.log(res.data[0].attr_vals);
      if(this.activeName=='many'){
        this.manyCateAttr=res.data;
      }else{
        this.onlyCateAttr=res.data;
      }
    },
    //添加属性/参数的窗口关闭时
    addDialogClosed(){
      //清空输入框
      this.$refs.addDialogRef.resetFields();
    },
    //点击确认按钮(添加属性/参数的窗口)
    async addDialog(){
      //发送请求  
      const {data:res}=await this.$http.post(`categories/${this.cateID}/attributes`,{
        attr_name:this.addDialogRuleForm.attr_name,
        attr_sel:this.activeName,
      });
      if(res.meta.status!=201) return this.$message.error('添加失败');
      this.$message.success('添加成功');
      //关闭窗口
      this.addDialogVisible = false;
      //重新获取页面
      this.getCateAttr();
    },
    //点击编辑按钮打开编辑窗口
    async showEditDialog(attr_id){
      const {data:res}=await this.$http.get(`categories/${this.cateID}/attributes/${attr_id}`,{attr_sel:this.activeName});
      if(res.meta.status!=200) return this.$message.error('获取失败');
      this.editDialogRuleForm.attr_name=res.data.attr_name;
      this.editDialogRuleForm.attr_id=res.data.attr_id;
      
      this.editDialogVisible=true;
    },
    //修改属性/参数的窗口关闭时
    editDialogClosed(){
      //清空输入框
      this.$refs.editDialogRef.resetFields();
    },
    //点击确认按钮(修改属性/参数的窗口)
    async editDialog(){
      //发送请求  
      const {data:res}=await this.$http.put(`categories/${this.cateID}/attributes/${this.editDialogRuleForm.attr_id}`,{
        attr_name:this.editDialogRuleForm.attr_name,
        attr_sel:this.activeName,
      });
      if(res.meta.status!=200) return this.$message.error('修改失败');
      this.$message.success('修改成功');
      //关闭窗口
      this.editDialogVisible = false;
      //重新获取页面
      this.getCateAttr();
     
    },
    //点击删除按钮
    async deleteCateAttr(attr_id){
    const result= await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err=>err);
      //点击取消
      if(result!='confirm'){
        return this.$message({
          type: 'info',
          message: '已取消删除'
        });   
      }else{
      //点击确认 
      const {data:res}=await this.$http.delete(`categories/${this.cateID}/attributes/${attr_id}`);
      if(res.meta.status!=200) return this.$message.error('删除失败');
      this.$message.success('删除成功');
      //重新获取页面
      this.getCateAttr();
      }
    },
    //输入框/按钮离开焦点/按回车时
    async handleInputConfirm(row){
      //如果输入框的内容无/无意义
      if(row.inputValue.trim().length==0){
        //输入框的内容置空
        row.inputValue='';
        row.inputVisible=false;
        return;
      };
      //将输入框的内容加入到属性值中
      row.attr_vals.push(row.inputValue.trim());
      //将输入框的内容置空
      row.inputValue='';
      //将按钮关闭
      row.inputVisible=false;
      this.saveAttr(row);
    },
    //点击输入按钮
    showInput(row){
      row.inputVisible=true;
      //输入框获得焦点
      //$nextTick方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //将保存的属性值，并提交到数据库
    async saveAttr(row){
      //发送请求
      const {data:res}=await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(','),
      });
      if(res.meta.status!=200) return this.$message.error('修改参数失败');
      this.$message.success('修改参数成功');
    },
    //删除属性tag
    handleClosed(index,row){
      row.attr_vals.splice(index,1);
      this.saveAttr(row);
    }
  },
  components: {

  },
  computed: {
    //tag标签是否选中的布尔值
    isTagButtonDisabled(){
      if(this.selectedCateKeys.length!==3) return true;
      return false;
    },
    //选中的商品ID值
    cateID(){
      if(this.selectedCateKeys.length===3) return this.selectedCateKeys[this.selectedCateKeys.length-1];
      return null;
    },
    //添加窗口的选用信息
    addInfo(){
      if(this.activeName=='many'){
        return '动态参数';
      }else{
        return '静态属性';
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>
